<?php
  global $cfg;
chdir(dirname(__FILE__)."/../..");
$path = getcwd();
chdir("../");
$path3 = getcwd();
chdir(dirname(__FILE__));
#debug($path3 , $path2);
include_once $path3."/lib/core.class.php";

#include_once $path."/core.php";


class CatalogList extends IPlugin
{
    var $color;

    function CatalogList($parent = null)
    {
        IPlugin::IPlugin($parent);
        $this->tplfolder = dirname(__FILE__)."/tpl";
        $this->color = "blue";
    }

    function getPluginTag() { return "cataloglist"; }
    function getPluginName() { return "Catalog List Plugin"; }
    function getPluginVersion() { return "1.0.0"; }

    function getProperty($p = null)
    {
        if(null == $p)
        {
            return array("MenuTitle", "MenuBlockTitle");
        }
        $result = "";
        switch ($p)
        {
            case "MenuBlockTitle": { return "Shopping cart"; } break;
            case "MenuTitle" : { return "Catalog map"; } break;
        };
        return $result;
    }

    function getFlag($name,&$ParamList){
            
      if( !in_array($name,array_keys($ParamList))){
                return 'N';
      }else{
         if('on' == $ParamList[$name]){
                  return 'Y';
              }

          }
       return 'N';       
    }    
    // ----------------------------------------------------------------------------------
    // --- [ Handling all actions ] -----------------------------------------------------
    // ----------------------------------------------------------------------------------

    function doAction($params)
    {
         
        if(null != ($result = IPlugin::doAction($params)))
        {
            return $result;
        }
        $arg = getCoreInstance();
        $arg = $arg->getGET();

        if("echo" == $arg["action"])
        {
            echo "CustomerList: echo: ".$arg["string"];
        }

        if("doEditCatalog" == $_POST["action"])
        {
            $z = $_POST;
                $sort = $z['sort'];
                unset($z['sort']);
            $uid = $z["id"];
            $catalog_id = $z['catalog_id'];
            
//          $copy_to = "uploads/".$z['parent_id']."_".$z['catalog_id']."_".$z['item_number']."_small.jpg";
            $copy_to = "uploads/".$z['catalog_id']."_small.jpg";
                        
                        @uploadFile('img_small',"/inventory/".$copy_to);
                        if(isne($_FILES['img_small']['tmp_name']))
            $z['img_small'] = $copy_to;

            unset($z["action"], $z["id"],$z['catalog_id']);

            $z["is_active"] = $this->getFlag("is_active",$z);
            $z["display_in_menu"] = $this->getFlag("display_in_menu",$z);

            $set = "";
            foreach ($z as $k => $v)
            {
                $set .= ($set=="" ? "" : ", ")."{$k} = '".str2db($v)."'";
            }

            $sql="update catalog set {$set} where catalog_id='{$catalog_id}'";

            $core = getCoreInstance();
            $db = $core->getProperty("db");
            $db->Exec($sql);

                
            $sql= "update catalogs_sorting set catalogs_sorting_sort_by = '$sort' where catalog_sorting_catalog_id = '{$catalog_id}'";
        
            $db->Exec($sql);
        }elseif ("doAddCatalog" == $_POST['action'])
        {
            $z = $_POST;
            $uid = $z["id"];
            $catalog_id = $z['catalog_id'];

            $z['parent_id'] = $_GET['catalog_id'];
//          $copy_to = "uploads/".$z['parent_id']."_".$z['catalog_id']."_".$z['item_number']."_small.jpg";
            
            unset($z["action"], $z["id"],$z['catalog_id']);
            
            $z["is_active"] = $this->getFlag("is_active",$z);
            $z["display_in_menu"] = $this->getFlag("display_in_menu",$z);

            $keys = "";
            $vars = "";
        
                $sort = $z['sort'];
                unset($z['sort']);

            foreach ($z as $k => $v)
            {
                $keys .=($keys=="" ? "" : ", ")."{$k}";
                $vars .=($vars=="" ? "" : ", ")."'".str2db($v)."'";
            }

            $keys .= ", is_category ";
            $vars .= ", 'Y' ";

            $sql="insert into catalog ({$keys}) values({$vars}) ";

            $core = getCoreInstance();
//            $core = $GLOBALS['core'];
            $db = $core->getProperty("db");
            $catalogthisid = $db->Exec($sql);

                        $sql = "insert into catalogs_sorting (catalog_sorting_catalog_id,catalogs_sorting_sort_by) values('{$catalogthisid}', '{$sort}')";
                        $id = $db->Exec($sql);  
                        
                        // image !!!!!!!!!!!!!!!!!!!!!!!!!!
                        $copy_to = "uploads/".$catalogthisid."_small.jpg";
                        @uploadFile('img_small',"/inventory/".$copy_to);
                        if(isne($_FILES['img_small']['tmp_name']))
                        $db->Exec("update catalog set img_small='$copy_to' where  catalog_id=$catalogthisid");  

        }elseif("swap" == $_POST['action'])
        {
            $chbx = $_POST['chbx'];
            $parent_id = $_REQUEST['catalog_id'];

            $core = getCoreInstance();
            $db = $core->getProperty("db");


            $q=" select catalog_id,sibling from catalog where parent_id='{$parent_id}' and catalog_id in ({$chbx[0]},{$chbx[1]})";
            $res = $db->getAll($q);

            $arg = array(
            array($res[1][sibling], $res[0][catalog_id]),
            array($res[0][sibling], $res[1][catalog_id]),
            );

            $db->Exec("update catalog set sibling=? where catalog_id=?",0, $arg);


        }elseif("insert_after" == $_POST['action'])
        {
            $chbx = $_POST['chbx'];
            $sibling_count = $_POST['sibling_count'];
            $parent_id = $_REQUEST['catalog_id'];

            $core = getCoreInstance();
            $db = $core->getProperty("db");
            $not_in =="";
            for($i = 0; $i<sizeof($chbx); $i++){
                $not_in .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
            }
            $q=" select catalog_id,sibling from catalog where parent_id='{$parent_id}' and sibling> '{$sibling_count}' and catalog_id not in ({$not_in})";
            $res = $db->getAll($q);

            $arg = array();
            for($i = 0 ; $i <sizeof($chbx);$i++){
                $arg[$i] = array(++$sibling_count,$chbx[$i]);
            }
            for($i = 0 ; $i <sizeof($res);$i++){
                $arg[] = array(++$sibling_count,$res[$i]['catalog_id']);
            }

            $db->Exec("update catalog set sibling=? where catalog_id=?",0, $arg);


        }elseif("insert_before" == $_POST['action'])
        {
            $chbx = $_POST['chbx'];
            $sibling_count = $_POST['sibling_count'];
            $parent_id = $_REQUEST['catalog_id'];

            $core = getCoreInstance();
            $db = $core->getProperty("db");
            $not_in =="";
            for($i = 0; $i<sizeof($chbx); $i++){
                $not_in .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
            }
            $q=" select catalog_id,sibling from catalog where parent_id='{$parent_id}' and sibling >= '{$sibling_count}' and catalog_id not in ({$not_in}) order by sibling";
            $res = $db->getAll($q);

            $arg = array();
            for($i = 0 ; $i <sizeof($chbx);$i++){
                $arg[$i] = array($sibling_count++,$chbx[$i]);
            }
            for($i = 0 ; $i <sizeof($res);$i++){
                $arg[] = array($sibling_count++,$res[$i]['catalog_id']);
            }
            $db->Exec("update catalog set sibling=? where catalog_id=?",0, $arg);

        }elseif("sibling_delete" == $_POST['action'])
        {
            $chbx = $_POST['chbx'];
            $sibling_count = $_POST['sibling_count'];
            $parent_id = $_REQUEST['catalog_id'];

            $core = getCoreInstance();
            $db = $core->getProperty("db");
            $not_in =="";
            for($i = 0; $i<sizeof($chbx); $i++){
                $not_in .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
            }
            $q="delete from catalog where catalog_id in ({$not_in})";
            $db->Exec($q);
        }elseif("move_to_folder" == $_POST['action'])
        {
            $chbx = $_POST['chbx'];
            $sibling_count = $_POST['sibling_count'];
            $parent_id = $_REQUEST['catalog_id'];

            $core = getCoreInstance();
            $db = $core->getProperty("db");
            $in =="";
            for($i = 0; $i<sizeof($chbx); $i++){
                $in .= ($i == 0 ? "" : ", ") . "'{$chbx[$i]}' " ;
            }
            $q="update catalog set parent_id='{$sibling_count}' where catalog_id in ({$in})";
            $db->Exec($q);
        }
        //doDeleteCatalog
        if("doDeleteCatalog" == $_GET['action'])
        {
            $uid = $_GET['id'];
            if(empty($uid) || $uid<0 || !is_numeric($uid) )
            {
                header("location: ./?".$this->getURL());
                exit();
            }
            $core = getCoreInstance();
            $db = $core->getProperty("db");

            $sql = "delete from catalog where catalog_id=".str2db($uid)."";
            $db->Exec($sql);

            $sql = "delete from catalogs_sorting where catalog_sorting_catalog_id='".str2db($uid)."'";
            $db->Exec($sql);

        }
    }


    // ----------------------------------------------------------------------------------
    // --- [ Render pages ] -------------------------------------------------------------
    // ----------------------------------------------------------------------------------

    function Render($params)
    {
        global $_G;
        if(null != ($result = IPlugin::Render($params)))
        {
            return $result;
        }

        $core = getCoreInstance();
        $render = $core->framework->smarty;
        $render->assign("baseurl", "?".$this->getURL()."&page=".$_G["page"]);

        $page = "";

        switch ($_G["page"]) {

            case "edit":
            $page = $this->renderCatalogEdit($render);
            break;

            case "add":
            $page = $this->renderCatalogAdd($render);
            break;

            default:
            $page = $this->renderCatalogList($render);
            break;
        }

        return $render->fetch("file:".$this->tplfolder."/".$page);
    }


    // ----------------------------------------------------------------------------------
    // --- [ Generate Catalogs List ] --------------------------------------------------
    // ----------------------------------------------------------------------------------

    function cb_renderCT($data)
    {
        global $cfg;
        $img_small = $data["img_small"];
        if( isne($img_small))
        {
//die(print_r($cfg[http_root]));
            $img_small = "<a href='?".$this->getURL()."&catalog_id=".$data["catalog_id"]."' ><img src='" . $cfg['http_root']. "/inventory/{$img_small}' border=0 /></a>";
        }
        else
        {
            $img_small = "No Image";
        }
        $catalog_id = $_GET['catalog_id'];
        if(isne($_GET['catalog_id']))
        {
            if($catalog_id<0 || !is_numeric($catalog_id)){
                header("location: ./?".$this->getURL());
                exit();
            }
        }
        else
        {
            $catalog_id = 0;
        }
        $dt = array(
        array("<input style='border:none;' type='checkbox' name='chbx[]' value='{$data["catalog_id"]}' />", "align='center' "),
        array($data["catalog_id"] , "align=\"center\""),
        array($data["sibling"] , "align=\"center\""),
        array($img_small , ""),
        array( "<a href='?".$this->getURL()."&catalog_id=".$data["catalog_id"]."' >".$data["title"]."</a>", ""),
        array('Y'==$data["is_active"]?"Yes":"No" , "align='center'"),
        array("<a href=\"?".$this->getURL()."&page=edit&catalog_id={$catalog_id}&id={$data[catalog_id]}\">edit</a>&nbsp;<a href=\"?".$this->getURL()."&action=doDeleteCatalog&id={$data[catalog_id]}\">delete</a>" , "align=\"center\"")
        );
        return $dt;
    }

    function renderCatalogList(&$render)
    {
        $core = &getCoreInstance();
        $db = $core->getProperty("db");

        
        $curent_catalog_id ;
        if( isne($_GET['catalog_id']))
        {
            $curent_catalog_id = $_GET['catalog_id'];
        }
        else
        {
            $curent_catalog_id = 0;
        }
        $sb = &$core->getSnippet("sibling");
        $sibling_params = array(
        "action"        =>"removeWrongSibling",
        "table"         =>"catalog",
        "sField"        =>"sibling", // ordering field
        "sId"           =>"catalog_id",
        "sParentId"     =>"parent_id",
        "sWhere"        =>"is_category = 'Y'",
        "sOrderBy"      =>"order by title",
        );
        $sb -> doAction($sibling_params);// remove sibling = -1
        
        // ===== end of  sibling = -1*/
        $hs = &$core->getSnippet("historylinks");
        $params = array(
        "startfrom" => $curent_catalog_id,
        "f_id" => "catalog_id",
        "f_parent" => "parent_id",
        "f_title" => "title",
        "table" => "catalog",
        "stopval" => 0, // root
        "url" => "?".$this->getURL()."&catalog_id=###", // ### will be replaced by id
        "html_root" => "Site Root",
        "html_url" => "?".$this->getURL(),
        "html_separatop" => " :: ",
        );
        $HTML1 = $hs->Render($params);
        $render->assign("catalog_hs", $HTML1."<br/>");
        $db_res = $db->getAll("select catalog_id, title,is_active,img_small,sibling from catalog where is_category='Y' and parent_id=".$curent_catalog_id." order by sibling");
        for($i = 0 ;$i<sizeof($db_res) ;$i++)
        {
            $db_res[$i] = $this->cb_renderCT($db_res[$i]);
        }

        $catalog_id = $_GET['catalog_id'];
        if(isne($_GET['catalog_id']))
        {
            if($catalog_id<0 || !is_numeric($catalog_id)){
                header("location: ./?".$this->getURL());
                exit();
            }
        }
        else
        {
            $catalog_id = 0;
        }
        $render->assign('catalogs',$db_res);
        $render->assign('title',"Catalogs list");
        $render->assign('add_url',"?".$this->getURL()."&catalog_id=".$catalog_id);
        $render->assign('empty_message',"No catalogs for items yet");
        //       Sibling
        getAllHistory(null,"",$res );

        $render->assign("folder_locations",$res);

        $res_folder_str = "";
        for($i= 0 ; $i < sizeof($res) ; $i++ )
        {
            $res_folder_str  .=trim( join("|",$res[$i]) );
            if($i != sizeof($res)-1)
            {
                $res_folder_str  .="||";
            }
            
        }
        $res_folder_str=str_replace("\r\n","",$res_folder_str);
        
        $res_folder_str ="0".$res_folder_str; /// root without id
    
        $sql_action = "select catalog_id,sibling, title from catalog where is_category = 'Y' and parent_id=".$curent_catalog_id." order by sibling ";
        $res_action = $db->getAll($sql_action );
        $res_action_str = "";
        for($i= 0 ; $i < sizeof($res_action) ; $i++ )
        {
            $res_action_str .= trim(join("|",$res_action[$i]));
            if($i != sizeof($res_action)-1)
            {
                $res_action_str .="||";
            }
        }
        $res_action_str=str_replace("\r\n","",$res_action_str);
        
        $render->assign('action_url',"?".$this->getURL()."&catalog_id=".$curent_catalog_id);
        $params = array
        (
        "action_url"    => "?".$this->getURL(),
        "action_list"   => array("swap","insert_after","insert_before","sibling_delete","move_to_folder"),
        "insert_list_str" => $res_action_str,
        "res_folder_str" => $res_folder_str,
        );
        $SB_HTML = $sb->Render($params);
        $render->assign('sibling',$SB_HTML);
        // eof sibling

        return "cataloglist.tpl.php";

    }/// renderCatalogList





    function renderCatalogEdit(&$render)
    {
        $core = &getCoreInstance();
        $db = $core->getProperty("db");
        $uid = $_GET["id"];
        if(empty($uid) || $uid<0 || !is_numeric($uid) )
        {
            header("location: ./?".$this->getURL());
            exit();
        }
        $catalog_id = $_GET['catalog_id'];
        if(isne($_GET['catalog_id']))
        {
            if($catalog_id<0 || !is_numeric($catalog_id)){
                header("location: ./?".$this->getURL());
                exit();
            }
        }
        else
        {
            $catalog_id = 0;
        }
        $hs = &$core->getSnippet("historylinks");
        $params = array(
        "startfrom" => $catalog_id,
        "f_id" => "catalog_id",
        "f_parent" => "parent_id",
        "f_title" => "title",
        "table" => "catalog",
        "stopval" => 0, // root
        "url" => "",
        "html_root" => "Site Root",
        "html_url" => "",
        "html_separatop" => " :: ",
        );
        $hs_edit = $hs->Render($params);

        $render->assign("url", "?".$this->getURL()."&catalog_id=".$catalog_id);
        $render->assign("cancel_url", "?".$this->getURL());
        $render->assign("id", $uid);
        $render->assign("parent_string", $hs_edit);
        $render->assign("action", 'doEditCatalog');
        $render->assign("title", 'Edit Catalog');

        $item = arraydb2str($db->getRow("select * from catalog where catalog_id={$uid}"));
        // -------------------------------
        $sBasePath = "/lib/fckeditor/";
        $oFCKeditor = new FCKeditor('short_desc');
        $oFCKeditor->BasePath   = $sBasePath;
        $oFCKeditor->ToolbarSet = "Basic"; // Optimum
        $oFCKeditor->Width      = 500;
        $oFCKeditor->Height     = 200;
        $oFCKeditor->Value      = db2str($item["short_desc"]);
        //$oFCKeditor->Create() ;

        $render->assign("stexteditor", $oFCKeditor->CreateHtml());


        $oFCKeditor = new FCKeditor('description');
        $oFCKeditor->BasePath   = $sBasePath;
        $oFCKeditor->ToolbarSet = "Default"; // Optimum
        $oFCKeditor->Width      = 500;
        $oFCKeditor->Height     = 450;
        $oFCKeditor->Value      = db2str($item["description"]);
        // -------------------------------
        //$render->assign("shortdesc", $item["shortdesc"]);

        $render->assign("ftexteditor", $oFCKeditor->CreateHtml());

        $sql = "select catalogs_sorting_sort_by from catalogs_sorting where catalog_sorting_catalog_id = '{$uid}'";
        $sort = $db->getone($sql);
        $render->assign("sort", $sort);

        $render->assign("item", $item);


        $sql = "select * from vendors";
        $vendors = $db->getall($sql);
        $render->assign("vendors", $vendors);
        


        return "catalogedit.tpl.php";
    }// renderCatalogEdit
    function renderCatalogAdd(&$render)
    {
        $core = &getCoreInstance();
        $db = $core->getProperty("db");

        $catalog_id = $_GET['catalog_id'];
        if(isne($_GET['catalog_id']))
        {
            if($catalog_id<0 || !is_numeric($catalog_id)){
                header("location: ./?".$this->getURL());
                exit();
            }
        }
        else
        {
            $catalog_id = 0;
        }
        $render->assign("url", "?".$this->getURL()."&catalog_id=".$catalog_id);
        $render->assign("cancel_url", "?".$this->getURL());
        $render->assign("action", 'doAddCatalog');
        $render->assign("title", 'Add Catalog');
        $sql = "select * from vendors";
        $vendors = $db->getall($sql);
        $render->assign("vendors", $vendors);

        return "catalogedit.tpl.php";
    }// renderCatalogAdd


};


?>